from odoo import fields, models, api

PUBLISH_CATEGORY = [('event_display', '活动展示'), ('notice', '公告'), ('other', '其他')]


class RpMarketingPublish(models.Model):
    _name = 'rp.marketing.publish'
    _description = '发布'
    _rec_name = 'code'

    name = fields.Char(string='名称', copy=False)
    code = fields.Char(string='序列号', default='RP_MPB/****', copy=False)
    publish_category = fields.Selection(string='展示分类', selection=PUBLISH_CATEGORY, copy=False)
    invite_plan_id = fields.Many2one(string='邀请计划', comodel_name='rp.invite.plan', copy=False)
    coupon_task_plan_id = fields.Many2one(string='优惠券计划', comodel_name='rp.marketing.coupon.task.plan', domain=[('actual_begin_date', '<=', fields.Date.today()), ('actual_end_date', '>=', fields.Date.today())], copy=False)
    publish_tag = fields.Boolean(string='发布', default=False, copy=False)
    modal_tag = fields.Boolean(string='弹窗', default=False, copy=False)

    cover_ids = fields.Many2many(string='封面', comodel_name='ir.attachment', relation='rp_marketing_publish_cover_ir_attachment_rel', copy=False)
    modal_img_ids = fields.Many2many(string='弹窗', comodel_name='ir.attachment', relation='rp_marketing_publish_modal_ir_attachment_rel', copy=False)

    copy_writing = fields.Html(string='文案', copy=False)
    link = fields.Char(string='链接', copy=False)
    publish_date = fields.Datetime(string='发布时间', copy=False, default=fields.Datetime.now())
    active_flag = fields.Boolean(string='有效', default=False)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].next_by_code('rp.marketing.publish') or '/'
        result_list = super(RpMarketingPublish, self).create(vals_list)
        for result in result_list:
            if result.publish_tag and result.coupon_task_plan_id:
                result.coupon_task_plan_id.enable_statue = True
        return result_list

    def write(self, vals):
        if not vals.get('publish_tag'):
            if self.coupon_task_plan_id:
                self.coupon_task_plan_id.write({'enable_statue': False})

    """
    Onchange
    """

    @api.onchange('modal_tag')
    def onchange_modal_tag(self):
        if not self.modal_tag:
            self.update({'modal_img_ids': False})

    """
    Button Function
    """

    def call_coupon_plan(self):
        vew_id = self.env.ref('rp_marketing_management.rp_marketing_coupon_task_plan_for_publish_form').id
        return {
            'type': 'ir.actions.act_window',
            'name': 'Coupon Plan',
            'res_model': 'rp.marketing.coupon.task.plan',
            'view_mode': 'form',
            'view_id': vew_id,
            'target': 'new'
        }
